#!/usr/bin/env bash

###########################
# Colours
###########################

export BOLD="\e[1m"

export CYAN="\e[36m"
export GREEN="\e[32m"
export YELLOW="\e[33m"
export RED="\e[31m"

export RESET="\e[0m"

###########################
# Functions
###########################

show_help ()
{
  echo ""
  echo "Pulls the installspace from the server to /opt/yujin/indigo."
  echo "Make sure you call this with sudo or set the correct permissions"
  echo "on /opt/yujin."
  echo ""
  echo "    Usage:"
  echo "        sudo groot_binaries <required-options> <options>"
  echo ""
  echo "    Required Option (one of):"
  echo "        --stable          : work with the stable binaries"
  echo "        --devel           : work with the devel binaries"
  echo ""
  echo "    Options:"
  echo "        --help            : this help message"
  echo "        --external        : use the external server instead of the internal one"
  echo "        --partners        : use the server for partners (stable only)"
  echo "        --list-rosdeps    : list all rosdep keys required by the groot binary installspace"
  echo "        --install-rosdeps : install all rosdeps required by the groot binary installspace"
  echo ""
  echo "    Admin Options:"
  echo "        --push            : push local /opt/yujin/indigo installspace with the server"
  echo ""
  exit 0
}

###########################
# Command Line
###########################

for i in "$@"
do
case $i in
    --help)
    SHOW_HELP=1
    shift
    ;;
    --list-rosdeps)
    LIST_ROSDEPS=1
    shift
    ;;
    --install-rosdeps)
    INSTALL_ROSDEPS=1
    shift
    ;;
    --external)
    EXTERNAL=1
    shift
    ;;
    --partner)
    PARTNERS=1
    shift
    ;;
    --partners)
    PARTNERS=1
    shift
    ;;
    --stable)
    STABLE=1
    shift
    ;;
    --devel)
    DEVEL=1
    shift
    ;;
    --continental)
    CONTINENTAL=1
    shift
    ;;
    --push)
    PUSH=1
    shift
    ;;
    *)
       # unknown option
    ;;
esac
done

###########################
# Aborts
###########################

if [ ! -z "$SHOW_HELP" ]; then
  show_help
  exit 0
fi

if [ -z "$STABLE" ] && [ -z "$DEVEL" ] && [ -z "$CONTINENTAL" ]; then
  echo ""
  echo "ERROR : you must set one of either --stable or --devel"
  echo ""
  exit 1
fi

###########################
# Variables
###########################

if [ ! -z "$STABLE" ]; then
  RELEASE="stable"
elif [ ! -z "$CONTINENTAL" ]
then
  RELEASE="continental"
else
  RELEASE="devel"
  if [ ! -z "$PARTNERS" ]; then
    echo ""
    echo "ERROR : partners may only access to stable"
    echo ""
    exit 1
  fi
fi

# put the <rosdistro> folder here, should eventually move it to /opt/yujin/amd64
export local_dir=/opt/yujin/amd64

if [ ! -z "$EXTERNAL" ]; then
  export remote_url=files@files.yujinrobot.com
  export remote_path=/data/file_server/rsync_repositories/yujin/amd64
elif [ ! -z "$PARTNERS" ]; then
  export remote_url=groot@files.yujinrobot.com
  export remote_path=/data/file_server/rsync_partner_repositories/yujin/amd64
else
  export remote_url=files@files.yujin.com
  export remote_path=shared/installspaces/yujin/amd64
fi
export remote_dir=${remote_url}:${remote_path}


# Options - you basically want to mostly replicate the -a option (good set of defaults), but we don't want owner transferred
# 
# --delete   : files from the destination directories
# --checksum : if files are the same size (but different timestamps), do a checksum on them to see whether to transfer or not 
#
# -a options we like:
#   --recursive : recurse into directories
#   --links     : copy symlinks as symlinks
#   --perms     : preserve permissions
#   --times     : preserve times (dont do this and it will always recopy)

export OPTIONS="--delete --recursive --links --compress --times --perms --checksum --verbose"

# not necessary now - it is the server's responsibility to not have these
#EXCLUDES=(
#  --exclude '*.pyc'
#)

if [ ! -z "$INSTALL_ROSDEPS" ]; then
    echo ""
    echo "Updating the rosdep cache"
    echo ""
    rosdep update
    echo ""
    echo "Installing all rosdeps required by the binaries installspace in ${local_dir}/indigo-${RELEASE}"
    echo ""
    echo "  Executing:"
    echo ""
    echo "    source ${local_dir}/indigo-${RELEASE}/setup.bash"
    echo "    rosdep install -r --default-yes --from-paths ${local_dir}/indigo-${RELEASE} --ignore-src"
    echo ""
    source ${local_dir}/indigo-${RELEASE}/setup.bash
    rosdep install -r --default-yes --from-paths ${local_dir}/indigo-${RELEASE} --ignore-src
    exit 0
fi

if [ ! -z "$LIST_ROSDEPS" ]; then
    echo ""
    echo "Listing all rosdep keys required by the binaries installspace in ${local_dir}/indigo-${RELEASE}"
    echo ""
    echo "  Executing:"
    echo ""
    echo "    source ${local_dir}/indigo-${RELEASE}/setup.bash"
    echo "    rosdep keys -r --from-paths ${local_dir}/indigo-${RELEASE} --ignore-src | sort"
    echo ""
    source ${local_dir}/indigo-${RELEASE}/setup.bash
    rosdep keys -r --from-paths ${local_dir}/indigo-${RELEASE} --ignore-src | sort
    exit 0
fi

if [ ! -z "$PUSH" ]; then
    echo ""
    echo "Pre-clearing *.pyc files from /opt/yujin/amd64/indigo-${RELEASE}"
    find ${local_dir}/indigo-${RELEASE} -name \*.pyc -delete
    echo ""
    echo "Pushing changes to the file server '${remote_dir}'."
    # Need to automate this script on jenkins.
    #echo "Do you really want to push changes (if you aren't sure, you definitely do not)?[y/N]:"
    #read answer
    #if [ "$answer" == "y" ]; then
        rsync ${OPTIONS} ${local_dir}/indigo-${RELEASE} ${remote_dir} | grep -E '^deleting|[^/]$'  # the grep is to remove directory only output to stdout (e.g. indigo-devel/share/rocon_concert/)
    #else
    #    echo "Aborting."
    #fi
    echo ""
else
    # SKIP - now we have rsync working properly, this is not entirely necessary
    # remote_listing=`ssh ${remote_url} ls ${remote_path}/indigo-${RELEASE}/build-*`
    # if [ $? -ne 0 ]; then
    #   echo -e ""
    #   echo -e "${RED}ERROR: could not connect to${RESET} ${BOLD}'$remote_url'${RESET}${RED}.\n     : are you on the network?\n     : do you have the DNS settings correct?${RESET}"
    #   echo -e ""
    #   exit 1
    # fi
    # export remote_timestamp=`echo ${remote_listing} | sed 's/.*\\///'`
    # export local_timestamp=`ls ${local_dir}/indigo-${RELEASE}/build-* 2>/dev/null | sed 's/.*\\///'`
    # if [ "${remote_timestamp}" == "${local_timestamp}" ]; then
    #   echo "Nothing to do: remote and local builds have the same timestamps."
    #   exit 0
    # fi
    echo ""
    echo "Clearing *.pyc files from /opt/yujin/amd64/indigo-${RELEASE}"
    find /opt/yujin/amd64/indigo-${RELEASE} -name \*.pyc -delete
    echo ""
    rsync ${OPTIONS} ${remote_dir}/indigo-${RELEASE} ${local_dir} | grep -E '^deleting|[^/]$'  # the grep is to remove directory only output to stdout (e.g. indigo-devel/share/rocon_concert/)
    if [ $? -ne 0 ]; then
      echo -e ""
      echo -e "${RED}ERROR: failed to sync with${RESET} ${BOLD}'$remote_url'${RESET}${RED}.\n     : are you on the network?\n     : do you have the DNS settings correct?${RESET}"
      echo -e ""
      exit 1
    fi
    # just in case the server misbehaved and sent us pyc files, clear them!
    find /opt/yujin/amd64/indigo-${RELEASE} -name \*.pyc -delete
    echo ""
    echo "You may need an additional 'groot_binaries --${RELEASE} --install-rosdeps' if there are new dependencies."
    echo ""
fi

